package com.fet.redeem.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.drools.KnowledgeBase;
import org.drools.runtime.StatefulKnowledgeSession;

import com.fet.redeem.dao.RedeemDao;
import com.fet.redeem.model.Customer;
import com.fet.redeem.model.Gift;
import com.fet.redeem.service.RedeemService;
import com.fet.redeem.util.StaticUtil;

public class RedeemServiceImpl implements RedeemService{

	private RedeemDao redeemDao;
	private KnowledgeBase kbase1;
	
	public RedeemServiceImpl(){
	}
	
	public RedeemDao getRedeemDao() {
		return redeemDao;
	}

	public void setRedeemDao(RedeemDao redeemDao) {
		this.redeemDao = redeemDao;
	}

	public KnowledgeBase getKbase1() {
		return kbase1;
	}

	public void setKbase1(KnowledgeBase kbase1) {
		this.kbase1 = kbase1;
	}
	
	public List<Customer> getAllCustList(){
		List<Customer> allCustList = StaticUtil.allCustList;
		if(allCustList == null){
			allCustList = redeemDao.getAllCustomers();
			StaticUtil.allCustList = allCustList;
			List<Gift> giftList = redeemDao.getAllGifts();
			Map<String,Gift> giftMap = new HashMap<String,Gift>();
			for(Gift gift:giftList){
				giftMap.put(gift.getId(), gift);
			}
			StaticUtil.giftMap = giftMap;
		}
		return allCustList;
	}
	
	public Customer getCustomerByName(String custName){
		List<Customer> allCustList = StaticUtil.allCustList;
		Customer customer = null;
		if(custName != null){
			for(Customer cust:allCustList){
				if(cust.getName() != null && custName.equals(cust.getName())){
					customer = cust;
					break;
				}
			}
		}
		return customer;
	}

	public Customer checkGift(Customer customer) {
		StatefulKnowledgeSession ksession1 = kbase1.newStatefulKnowledgeSession();
		ksession1.insert(customer);
		ksession1.startProcess("com.redeem.checkGiftFlow");
		ksession1.fireAllRules();
		ksession1.dispose();
		
		return customer;
	}

	public Gift getGiftById(String giftId) {
		Gift gift = null;
		if(giftId != null){
			gift = StaticUtil.giftMap.get(giftId);
			if(gift == null){
				gift = new Gift();
				gift.setId(giftId);
				gift.setName(giftId);
				gift.setPrice("100.00");
			}
		}
		return gift;
	}
	
}
